<template>
  <a-modal v-model:open="open"
           width="80%"
           :footer="null"
           :title="title"
           :keyboard="false"
           :mask-closable="false"
           @cancel="handleClose">
    <a-form
        :model="formState"
        name="basic"
        class="mt20"
        layout="horizontal"
        style="width: 100%;"
        ref="formRef"
        :rules="rules"
        :label-col=" { style: { width: '150px' } }"
        :wrapper-col="{ span: 24}"
        autocomplete="off"
    >
      <a-row class="flex justify-center">
        <a-col :span="18">
          <a-form-item
              label="父级权限"
              name="parentId"
          >
            <a-select
                ref="select"
                placeholder="请选择"
                allow-clear
                :key="new Date().getTime()"
                v-model:value="formState.parentId"
            >
              <template v-for="(apis,index) in apisList" :key="index">
                <a-select-option :value="apis.id">{{apis.title}}</a-select-option>
              </template>
            </a-select>
          </a-form-item>

          <a-form-item
              label="权限标题"
              name="title"
          >
            <a-input v-model:value.trim="formState.title" maxlength="60" placeholder="请输入权限名称"/>
          </a-form-item>

          <a-form-item
              label="权限代号"
              name="code"
          >
            <a-input v-model:value.trim="formState.code" maxlength="100" placeholder="请输入权限代号"/>
            <p  class="mt5 fb">代号建议从：A-Z 四位数，比如：A001，B001</p>
          </a-form-item>

          <a-form-item
              label="权限访问路径"
              name="path"
          >
            <a-input v-model:value.trim="formState.path" maxlength="200" placeholder="请输入权限访问路径"/>
          </a-form-item>

          <a-form-item
              label="权限请求方式"
              name="method"
          >
            <a-select
                ref="select"
                placeholder="请选择权限请求方式"
                allow-clear
                v-model:value="formState.method"
            >
                <a-select-option value="POST">POST</a-select-option>
                <a-select-option value="GET">GET</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
              label="权限排序"
              name="sorted"
          >
            <a-input v-model:value.trim="formState.sorted" maxlength="111" placeholder="请输入权限排序"/>
          </a-form-item>

          <a-form-item
              label="状态"
              name="status"
          >
            <a-switch v-model:checked="formState.status"
                      :checked-value="1"
                      :un-checked-value="0"
                      checked-children="显示"
                      un-checked-children="隐藏"/>
          </a-form-item>
          <a-form-item>
            <a-button style="margin-left: 150px" type="primary" @click.stop.prevent="onSubmit">
              <EditOutlined v-if="formState.id "></EditOutlined>
              <PlusOutlined v-else></PlusOutlined>
              {{ formState.id ? '更新权限' : '保存权限' }}
            </a-button>
            <a-button style="margin-left: 10px" danger type="primary" @click.stop.prevent="handleClose">
              <close-outlined></close-outlined>
              关闭
            </a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script setup>
/*
*   添加一级权限：parentId=0
*   编辑权限：parentId>=0
*   添加子权限:parentId>0
* */
const title = ref("添加一级权限")
const open = ref(false);
const formRef = ref({})
const emits = defineEmits(["success"])
const apisList = ref([])
const formState = ref({
  title: "",
  path: "/admin/v1/访问路由",
  code:"",
  status: 1,
  sorted: 1,
  method:"POST",
  parentId: 0
});

// 验证规则
const rules = {
  title: [{required: true, message: '请输入账号', trigger: 'change'}],
  path: [{required: true, message: '请输入路径', trigger: 'change'}],
  code: [{required: true, message: '请输入编号', trigger: 'change'}],
};

const onSubmit = async () => {
  try {
    await formRef.value.validate()
    if (formState.value.id) {
      await useUpdateApisDataApi(formState.value)
    } else {
      await useSaveApisDataApi(formState.value)
    }
    useMessage().success("操作成功")
    handleClose()
    emits("success")
  } catch (e) {
    useMessage().error(e.msg)
  }
};

const handleOpen = async (record) => {
  open.value = true
  const resp = await userLoadApisApi({})
  apisList.value = resp.data
  apisList.value.unshift({id:0,title:"根权限"})
  if(record && record.id){
    title.value = "编辑权限"
    const resp2 = await useGetApisDataApi(record.id)
    formState.value = resp2.data;
    if(record.parentId==0) {
      formState.value.parentId = record.parentId * 1
    }
  }
}

// 添加子权限
const handleAddChildOpen = async (record) => {
  title.value = "添加子权限"
  const resp = await userLoadApisApi({})
  apisList.value = resp.data
  var len = record.children?.length + 1 || 1
  formState.value = {
    id: "",
    title: "",
    code:record.code,
    path:"/admin/v1/访问路由",
    status: 1,
    sorted: len,
    method:"POST",
    parentId: record.id
  }

  open.value = true
}

const handleClose = () => {
  open.value = false
  apisList.value = []
  title.value = "添加一级权限"
  formRef.value.clearValidate()
  formRef.value.resetFields()
  formState.value = {
    id: "",
    title: "",
    path:"/admin/v1/访问路由",
    code: "",
    status: 1,
    method:"POST",
    sorted: 1,
    parentId: 0
  }
}

defineExpose({
  handleOpen,
  handleAddChildOpen
})
</script>

<style lang="scss" scoped>
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }

  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
    overflow: auto;
    border-radius: 0px;
  }

  :where(.css-dev-only-do-not-override-1hsjdkk).ant-modal .ant-modal-header {
    background: transparent;
  }

  .ant-modal-body {
    flex: 1;
  }
}
</style>